package com.example.messengerapp.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.messengerapp.databinding.ItemMessageBinding


class MessageAdapter(
    private val onMessageClick: (ChatFragment.Message) -> Unit,
    private val onImageClick: (String) -> Unit
) : ListAdapter<ChatFragment.Message, MessageAdapter.MessageViewHolder>(DiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
        val binding = ItemMessageBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MessageViewHolder(binding)
    }

    override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
        val message = getItem(position)
        holder.bind(message)
    }

    inner class MessageViewHolder(private val binding: ItemMessageBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bind(message: ChatFragment.Message) {
            with(binding) {
                if (message.text != null) {
                    textViewMessage.text = message.text
                    textViewMessage.visibility = View.VISIBLE
                    imageViewMessage.visibility = View.GONE
                } else if (message.imageUrl != null) {
                    Glide.with(imageViewMessage.context).load(message.imageUrl).into(imageViewMessage)
                    textViewMessage.visibility = View.GONE
                    imageViewMessage.visibility = View.VISIBLE

                    imageViewMessage.setOnClickListener {
                        onImageClick(message.imageUrl)
                    }
                }

                root.setOnClickListener {
                    onMessageClick(message)
                }
            }
        }
    }

    class DiffCallback : DiffUtil.ItemCallback<ChatFragment.Message>() {
        override fun areItemsTheSame(oldItem: ChatFragment.Message, newItem: ChatFragment.Message): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: ChatFragment.Message, newItem: ChatFragment.Message): Boolean {
            return oldItem == newItem
        }
    }
}
